package cn.ivicar.message.push.controller;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.ivicar.message.push.service.NotificationService;

public class NotificationController {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(NotificationController.class);

	@Inject
	private NotificationService notificationService;

	public void register(Long appId, Long customerId, String clientId, String clientTypeStr) throws CarsmartException {

		Integer clientType = validateParam(appId, customerId, clientId, clientTypeStr);

		try {
			notificationService.register(appId, customerId, clientId, clientType);
		} catch (Exception e) {
			LOGGER.warn(String.format("注册推送失败，[appId=%s][customerId=%s][clientId=%s][clientType=%s]", appId, customerId,
					clientId, clientType), e);
		}

	}

	private Integer validateParam(Long appId, Long customerId, String clientId, String clientTypeStr)
			throws BadRequestException {
		if (appId == null) {
			throw new BadRequestException("400", "请输入appId!");
		}

		if (customerId == null) {
			throw new BadRequestException("400", "请输入customerId!");
		}
		if (StringUtils.isBlank(clientId)) {
			throw new BadRequestException("400", "请输入clientId!");
		}
		if (StringUtils.isBlank(clientTypeStr)) {
			throw new BadRequestException("400", "请输入clientType!");
		}

		Integer clientType;
		try {
			clientType = Integer.parseInt(clientTypeStr);
		} catch (NumberFormatException e) {
			throw new BadRequestException("400", "请输入正确的clientType");
		}

		if (clientType.intValue() != 0 && clientType.intValue() != 1) {
			throw new BadRequestException("400", "请输入正确的clientType");
		}

		return clientType;
	}

	public void logout(Long appId, Long customerId, String clientId, String clientTypeStr) throws CarsmartException {
		Integer clientType = validateParam(appId, customerId, clientId, clientTypeStr);

		try {
			notificationService.logout(appId, customerId, clientId, clientType);
		} catch (Exception e) {
			LOGGER.warn(String.format("退出推送失败，[appId=%s][customerId=%s][clientId=%s][clientType=%s]", appId, customerId,
					clientId, clientType), e);
		}
	}
	
	

}
